<!-- 新增编辑部门 -->
<template>
  <div>
    <el-dialog
      :title="isAdd == 1 ? '添加渠道' : '编辑渠道信息'"
      :visible.sync="addEditVisible"
    >
      <el-form
        class="formView"
        ref="form"
        :model="formData"
        label-position="right"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="渠道类型:" prop="channelType">
          <el-autocomplete
            class="inline-input"
            v-model="formData.channelType"
            :fetch-suggestions="queryType"
            placeholder="渠道类型"
            :disabled="isAdd == 2 && !!formIds.channelName"
            @select="handleSelect($event, 'channelType')"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item
          label="渠道名称:"
          v-if="
            (isAdd == 1 && formIds.channelType) ||
              (isAdd == 2 && formIds.channelName)
          "
          prop="channelName"
        >
          <el-autocomplete
            class="inline-input"
            v-model="formData.channelName"
            :fetch-suggestions="queryChannelName"
            :disabled="!!formIds.channelDetail && isAdd == 2"
            placeholder="渠道名称"
            @select="handleSelect($event, 'channelName')"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item
          label="渠道细分"
          v-if="
            (isAdd == 1 && formIds.channelName) ||
              (isAdd == 2 && formIds.channelDetail)
          "
          prop="channelDetail"
        >
          <el-input
            v-model="formData.channelDetail"
            clearable
            placeholder="渠道细分"
          >
          </el-input>
        </el-form-item>

        <!-- <el-form-item label="排序:" prop="sort">
          <el-input
            v-model="formData.sort"
            clearable
            placeholder="排序"
          ></el-input>
        </el-form-item> -->

        <el-form-item
          label="渠道状态:"
          prop="state"
          v-if="
            (isAdd == 1 && formIds.channelName) ||
              (isAdd == 2 && formIds.channelDetail)
          "
        >
          <el-switch
            v-model="formData.state"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
          {{ formData.state ? ' 开启' : ' 禁用' }}
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getChannelType, editChannel } from '@/api/channelManage'
export default {
  components: {},
  props: {
    isAdd: {
      type: Number,
      default() {
        return 1
      }
    },
    detailData: {
      type: Object,
      default() {
        return {}
      }
    },
    channelId: [String, Number]
  },
  data() {
    return {
      addEditVisible: false,
      formData: {
        channelType: '',
        channelName: '',
        channelDetail: '',
        state: true
      },
      formIds: {
        channelType: '',
        channelName: '',
        channelDetail: ''
      },
      channelPlatformList: [],
      channelTypeList: [],
      rules: {}
    }
  },
  created() {},
  mounted() {},
  methods: {
    handleSelect(item, key) {
      setTimeout(() => {
        this.$set(this.formIds, key, item.key)
      }, 0)
    },
    // 获取渠道类型
    queryType(queryString, callback) {
      this.getChannelList(0, callback, queryString)
    },
    getChannelList(id, callback, queryString) {
      if (id || id === 0) {
        if (!queryString && this.isAdd == 1) {
          getChannelType({ channelParentId: id }).then(res => {
            callback(
              res.data.map(item => ({
                value: item.channelTypeName,
                key: item.channelTypeId
              }))
            )
          })
        } else {
          callback([])
        }
      }
    },
    // 获取渠道名称
    queryChannelName(queryString, callback) {
      this.getChannelList(this.formIds.channelType, callback, queryString)
    },
    submitForm(formName) {
      let submitData = {}
      //新增渠道
      if (this.isAdd == 1) {
        submitData.parentId =
          this.formIds.channelName || this.formIds.channelType || 0
        if (this.formIds.channelType) {
          if (this.formIds.channelName) {
            if (this.formData.channelDetail) {
              //添加渠道细分
              submitData.channelTypeName = this.formData.channelDetail
            } else {
              this.$message({ type: 'error', message: '请输入渠道细分' })
            }
          } else {
            if (this.formData.channelName) {
              submitData.channelTypeName = this.formData.channelName
              //添加渠道名称
            } else {
              this.$message({ type: 'error', message: '请输入渠道名称' })
            }
          }
        } else {
          // 添加渠道类型
          if (this.formData.channelType) {
            //添加渠道名称
            submitData.channelTypeName = this.formData.channelType
          } else {
            this.$message({ type: 'error', message: '请输入渠道类型' })
          }
        }
      } else {
        //修改渠道
        submitData.parentId =
          this.detailData.parentId3 ||
          this.detailData.parentId2 ||
          this.detailData.parentId1
        const errMeg = {
          channelDetail: '请输入渠道细分',
          channelName: '请输入渠道名称',
          channelType: '请输入渠道类型'
        }
        const result = Object.keys(this.formIds).every(key => {
          //id存在则文本必须存在且不可为空
          if (this.formIds[key]) {
            if (!this.formData[key]) {
              this.$message({ type: 'error', message: errMeg[key] })
            }
            return Boolean(this.formData[key])
          }
          return true
        })
        if (!result) return
        submitData.channelTypeName =
          this.formData.channelDetail ||
          this.formData.channelName ||
          this.formData.channelType
      }

      if (this.isAdd == 2) {
        submitData.channelTypeId =
          this.formIds.channelDetail ||
          this.formIds.channelName ||
          this.formIds.channelType
      }
      submitData.state = this.formData.state ? 1 : 0

      if (!submitData.channelTypeName) {
        return
      } else {
        this.onSubmit(submitData)
      }
    },
    onSubmit(data) {
      editChannel(data).then(res => {
        this.$message({
          message: this.isAdd == 1 ? '新增成功' : '修改成功',
          type: 'success'
        })
        this.addEditVisible = false
        this.$parent.getDataList()
        this.resetForm()
        this.$parent.refresh = !this.$parent.refresh
      })
    },
    resetForm(formName) {
      // this.$refs[formName].resetFields()
      this.formData = {
        channelType: '',
        channelName: '',
        channelDetail: '',
        state: true
      }
      this.resetRealForm()
      //this.addEditVisible = false
    },
    resetRealForm() {
      this.formIds = {
        channelType: '',
        channelName: '',
        channelDetail: ''
      }
    }
  },
  watch: {
    addEditVisible: {
      deep: true,
      handler(now, old) {
        if (now) {
          if (this.isAdd == 2) {
            const {
              state3,
              channelTypeName1: channelType,
              channelTypeName2: channelName,
              channelTypeName3: channelDetail,
              channelTypeId1: channelTypeId,
              channelTypeId2: channelNameId,
              channelTypeId3: channelDetailId
            } = this.detailData
            const formData = {
              channelDetail,
              state: state3 != 0,
              channelType,
              channelName
            }
            const ids = {
              channelType: channelTypeId,
              channelName: channelNameId,
              channelDetail: channelDetailId
            }
            Object.keys(formData).forEach(key => {
              this.formData[key] = formData[key]
            })
            Object.keys(ids).forEach(key => {
              this.formIds[key] = ids[key]
            })

            //this.formData = Object.assign({}, this.formData, this.detailData)
          }
        } else {
          this.resetForm()
        }
      }
    },
    'formData.channelType': {
      handler(now, old) {
        if (this.isAdd != 2) {
          this.resetRealForm()
          this.formData.channelName = ''
          this.formData.channelDetail = ''
        }
        const str = now.replace(/\s/g, '')
        this.formData.channelType = str.length <= 12 ? str : str.substr(0, 12)
      }
    },
    'formData.channelName': {
      handler(now) {
        if (now) {
          if (this.isAdd != 2) {
            this.formIds.channelName = ''
          }
          const str = now.replace(/\s/g, '')
          this.formData.channelName = str.length <= 12 ? str : str.substr(0, 12)
        }
      }
    },
    'formData.channelDetail': {
      handler(now) {
        if (now) {
          const str = now.replace(/\s/g, '')
          this.formData.channelDetail =
            str.length <= 12 ? str : str.substr(0, 12)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-dialog {
    width: 500px;
    border-radius: 10px;
  }
  .el-dialog__title {
    font-size: 16px;
  }
  .el-input {
    width: 250px;
  }
  .el-dialog__body {
    padding-top: 0;
    padding-bottom: 0px;
  }
  .el-form {
    padding: 10px 0;
  }
  .el-input__inner {
    height: 35px;
    line-height: 35px;
  }
  .el-form-item {
    margin-bottom: 15px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-dialog__footer {
    padding-top: 10px;
    padding-bottom: 10px;
    border-top: 1px solid #eee;
  }
}
.formView {
  border-top: 1px solid #eee;
  .sortInput {
    width: 100px;
  }
}
</style>
